import time
from Simplified_code.utils.util import *
import numpy as np
import datetime


def write_timestamp(t, idx1, idx2, starttime, ts_file):
    print("开始write_timestamp")
    fp_timestamp = np.asarray([t[int(np.mean((idx1[j], idx2[j])))] for j in range(len(idx1))])
    for ts in fp_timestamp:
        print(ts)
        print(starttime)
        print(starttime+ts)
        ts_file.write(str(starttime + ts) + '\n')


def normalize_and_fingerprint(haar_images, fp_file):
    std_haar_images = fp_feature.standardize_haar(haar_images, type='MAD')
    binaryFingerprints = fp_feature.binarize_vectors_topK_sign(std_haar_images,
                                                               K=dict_json['fingerprint']['k_coef'])
    # Write to file
    b = np.packbits(binaryFingerprints)
    fp_file.write(b.tobytes())

# 读取生成的mad文本文件
def init_MAD_stats(mad_fname):
    ntimes = get_ntimes(dict_json)
    fp_feature.haar_medians = np.zeros(dict_json['fingerprint']['nfreq'] * ntimes)
    fp_feature.haar_absdevs = np.zeros(dict_json['fingerprint']['nfreq'] * ntimes)
    f = open(mad_fname, 'r')
    for i, line in enumerate(f.readlines()):
        nums = line.split(',')
        fp_feature.haar_medians[i] = float(nums[0])
        fp_feature.haar_absdevs[i] = float(nums[1])
    f.close()


if __name__ == '__main__':
    print('mad已经计算完毕，接下来生成指纹')
    t_start = time.time()
    path = './data/waveformscegun/fp_input_cegun.json'
    dict_json = load_json_file(path)
    fname = dict_json['data']['fingerprint_files'][0]
    print(fname)

    # print(dict_json)
    fp_feature = init_feature_extractor(dict_json)
    print(fp_feature.__dict__)

    mad_name = gen_mad_fname(dict_json)
    print(mad_name)
    init_MAD_stats(mad_name)

    fp_folder, ts_folder = get_fp_ts_folders(dict_json)
    print(fp_folder)
    print(ts_folder)
    init_folder([fp_folder, ts_folder])

    path = dict_json['data']['folder'] + fname
    data_list, duration, start_time, end_time = read_csv(path)
    # print(data_list)
    # print(duration)

    ts_file = open(ts_folder + get_ts_fname(fname), "w")
    fp_file = open(fp_folder + get_fp_fname(fname), "wb")
    time_padding = get_partition_padding(dict_json)
    print(time_padding)
    min_fp_length = get_min_fp_length(dict_json)
    print(min_fp_length)

    if end_time - start_time < min_fp_length:
        print('数值序列过短，调整指纹长度参数')

    else:
        s = start_time
        i=0
        while end_time - s > min_fp_length:
            dt = dict_json['performance']['partition_len']
            e = min(s + dt, end_time)
            e_padding = min(s + dt + time_padding, end_time)

            #todo 分区问题
            haar_images, nWindows, idx1, idx2, Sxx, t = fp_feature.data_to_haar_images(data_list)
            write_timestamp(t, idx1, idx2, s, ts_file)
            print('haar_images:',haar_images)
            normalize_and_fingerprint(haar_images, fp_file)
            s = e
            i+=1
        ts_file.close()
        fp_file.close()
        print(i)
        t_end = time.time()
        print("Binary fingerprints took: %.2f seconds" % (t_end - t_start))
